package com.originskyseed.platform.log.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.log.i18n.LogResponseMsg;
import com.originskyseed.platform.log.model.LoginLog;
import com.originskyseed.platform.log.service.ILoginLogService;
import com.originskyseed.platform.log.vo.request.OperLogRequestVO;

/**
 * @Description
 * @Author Tangwh
 * @Version V1.0
 **/
@Controller
@RequestMapping("/loginLog")
@BaseLocaleResource(localeFileName = "i18n_log")
public class LoginLogController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(LoginLogController.class);

	@DubboReference
	ILoginLogService loginLogService;

	/**
	 * 用户登录日志分页查询列表
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/loginLogPageList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody loginLogPageList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			OperLogRequestVO requestVO = this.getParameterBean(OperLogRequestVO.class);
			// 分页查询
			BasePage<LoginLog> page = new BasePage<LoginLog>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.loginLogService.getLoginLogList(requestVO.toMap(), page);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), LogResponseMsg.LOG_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LogResponseMsg.LOG_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 导出日志信息Excel
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/logExport.json")
	public BaseResponseBody logExport(HttpServletRequest request, HttpServletResponse response) {
		BaseResponseBody result = null;
		String fileName = null;
		String sheetName = null;
		try {
			// 请求对象
			OperLogRequestVO requestVO = this.getParameterBean(OperLogRequestVO.class);
			List<LoginLog> list = this.loginLogService.selectListByMap(requestVO.toMap());
			// excel标题
			String[] title = { "用户名称", "访问IP", "登录地址", "来源 1推广类/公会、2内容类/家族、3合作类", "登录时间" };
			if ("1".equals(requestVO.getLogType())) {
				fileName = "用户登录日志" + System.currentTimeMillis() + ".xls";
				// sheet名
				sheetName = "用户登录日志";
			}
			String[][] values = new String[list.size()][];
			for (int i = 0; i < list.size(); i++) {
				values[i] = new String[title.length];
				// 将对象内容转换成string
				LoginLog obj = list.get(i);
				values[i][0] = obj.getUserName();
				values[i][1] = obj.getIp();
				values[i][2] = obj.getAddress();
				values[i][3] = obj.getSourceSys() + "";
				values[i][4] = DateFormatUtils.format(obj.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
			}
			outPutExcel(response, title, fileName, sheetName, values);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), LogResponseMsg.LOG_EXPORT_SUCCESS.getMsg()), null);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), LogResponseMsg.LOG_EXPORT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;

	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		OutputStream os = null;
		try {
			HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
			// 将文件存到指定位置
			this.setResponseHeader(response, fileName);
			os = response.getOutputStream();
			wb.write(os);
			os.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}

	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

}
